﻿using System;
using System.Collections.Generic;
using System.Linq;
using DT.Core.Models;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Furion.LinqBuilder;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using StackExchange.Profiling.Internal;
using XCPFrame.Core.Enums;
using XCPFrame.Core.ViewModels;

namespace XCPFrame.Application.Api
{
    /// <summary>
    /// 角色权限管理
    /// </summary>
    [AppAuthorize, ApiDescriptionSettings("角色权限管理")]
    public class RoleApiService : IDynamicApiController
    {
        private readonly ISqlSugarRepository repository;
        private readonly SqlSugarClient db;


        public RoleApiService(ISqlSugarRepository sqlSugarRepository)
        {
            repository = sqlSugarRepository;
            db = repository.Context;
        }

        /// <summary>
        /// 添加修改角色
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public int AddRole(SysRole role)
        {
            int rs = 0;

            if (role.Id == 0)
            {
                //node.Id = new SysNode().Id;
                bool sucess = db.Insertable<SysRole>(role).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandIdentityIntoEntity();
            }
            else
            {
                rs = db.Updateable(role).ExecuteCommand();
            }

            return rs;
        }

        /// <summary>
        /// 分页加载角色列表
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        public PagedList<SysRole> PostRoleListByPage(SearchByPageViewModel<SysRole> searchModel)
        {
            int totalCount = 0;

            if (searchModel.queryParams == null) { throw Oops.Oh(SystemErrorCodes.E0008); }

            string sql = "";

            List<SysRole> list;

            //注意：SugarParameter 参数名必须带@，值默认带单引号。
            sql = "select * from sys_role  where delete_flag=0 ";

            List<SugarParameter> param = new List<SugarParameter>();

            if (!searchModel.queryParams.Name.IsNullOrWhiteSpace())
            {
                sql += " and name like @name ";
                param.Add(new SugarParameter("@name", "%" + searchModel.queryParams.Name + "%"));
            }

            list = db.SqlQueryable<SysRole>(sql).AddParameters(param)
            .ToPageList(searchModel.pageIndex, searchModel.pageSize, ref totalCount);

            //}

            PagedList<SysRole> rs = new PagedList<SysRole>();

            rs.Items = list;

            rs.TotalCount = totalCount;

            rs.PageSize = searchModel.pageSize;

            return rs;
        }

        /// <summary>
        /// 获取全部角色列表
        /// </summary>
        /// <returns></returns>
        public List<SysRole> getAllRoles()
        {
            return db.Queryable<SysRole>().Where(i => i.DeleteFlag == false).ToList();
        }

        /// <summary>
        /// 批量逻辑删除角色
        /// </summary>
        /// <param name="roles"></param>
        /// <returns>是否成功</returns>
        public int DeleteRoles(List<SysRole> roles)
        {
            int rs = 0;

            if (roles.Count == 0) throw Oops.Oh(SystemErrorCodes.E0003);

            roles.ForEach(i => i.DeleteFlag = true);

            rs = db.Updateable(roles).UpdateColumns(it => new { it.DeleteFlag }).ExecuteCommand();

            return rs;
        }

        private List<SysRoleNode> sys_role_list = new List<SysRoleNode>();

        private void LookInNode(List<SysNode> nodes, int roleid)
        {
            foreach (SysNode node in nodes)
            {
                SysRoleNode record = new SysRoleNode();
                record.RoleId = roleid;
                record.NodeId = node.Id;
                sys_role_list.Add(record);

                if (!node.Children.IsNullOrEmpty() && node.Children.Count > 0)
                {
                    LookInNode(node.Children, roleid);
                }
                else
                {
                    continue;
                }

            }
        }

        /// <summary>
        /// 保存角色目录节点配置
        /// </summary>
        /// <param name="nodes"></param>
        /// <param name="roleid"></param>
        /// <returns></returns>
        public int AddRoleNodeList(List<SysNode> nodes, int roleid)
        {

            LookInNode(nodes, roleid);

            //先清空
            db.Deleteable<SysRoleNode>().Where(i => i.RoleId == roleid).ExecuteCommand();

            db.Insertable<SysRoleNode>(sys_role_list).ExecuteCommand();

            return 0;
        }


        /// <summary>
        /// 使用递归方法建树
        /// </summary>
        public static List<SysNode> BulidTreeByList(List<SysNode> list, List<SysNode> tree, int pid)
        {
            tree = new List<SysNode>();

            List<SysNode> rootList = list.Where(c => c.Pid == pid).ToList();

            foreach (SysNode rootnode in rootList)
            {
                SysNode node = new SysNode();
                node.Id = rootnode.Id;
                node.Pid = rootnode.Pid;
                node.Name = rootnode.Name;
                node.Title = rootnode.Title;
                node.Icon = rootnode.Icon;
                node.Jump = rootnode.Jump;
                node.Spread = rootnode.Spread;
                node.OrderNo = rootnode.OrderNo;
                node.Path = rootnode.Path;
                node.Level = rootnode.Level;
                node.List = BulidTreeByList(list, tree, node.Id);
                tree.Add(node);
            }

            return tree;
        }

        /// <summary>
        /// 获取角色菜单信息
        /// </summary>
        /// <param name="roleid"></param>
        /// <returns></returns>
        public List<SysNode> GetNodeTree(int roleid = 0)
        {
            List<SysNode> list, rs = new List<SysNode>();

            list = db.Queryable<SysRoleNode, SysNode>((m, n) => new JoinQueryInfos(
               JoinType.Left, m.NodeId == n.Id
               )).Where(m => m.RoleId == roleid).Select((m, n) => new SysNode
               {
                   Id = n.Id,
                   Title = n.Title,
                   Name = n.Name,
                   Icon = n.Icon,
                   Jump = n.Jump,
                   Spread = n.Spread,
                   Pid = n.Pid,
                   OrderNo = n.OrderNo,
                   Path = n.Path,
                   Level = n.Level
               }).ToList();

            rs = BulidTreeByList(list, rs, 0);

            return rs;
        }

        /// <summary>
        /// 获取全目录并显示角色权限
        /// </summary>
        /// <param name="roleid"></param>
        /// <returns></returns>
        public List<SysNode> GetNodeTreeWithRole(int roleid = 0)
        {
            List<SysNode> rs = new List<SysNode>();

            rs = db.Queryable<SysNode, SysRoleNode>((n, r) => new JoinQueryInfos(
                JoinType.Left, n.Id == r.NodeId && r.RoleId == roleid
                )).Select((n, r) => new SysNode
                {
                    Id = n.Id,
                    Title = n.Title,
                    Name = n.Name,
                    Icon = n.Icon,
                    Jump = n.Jump,
                    Spread = n.Spread,
                    Pid = n.Pid,
                    OrderNo = n.OrderNo,
                    Path = n.Path,
                    Level = n.Level,
                    Checked = SqlFunc.IF(r.NodeId > 0).Return(true).End(false)
                }).ToTree(it => it.Children, it => it.Pid, 0);

            return rs;
        }

    }
}
